import {Component, OnDestroy, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {ArticleInterface, ArticlesManagerService} from '../../manager-business/articles-manager.service';
import {ComponentViewEnm, ComponetViewManagerService} from '../../../business/componet-view-manager.service';
import {Subscription} from 'rxjs';
import {NzModalService} from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-manager',
  templateUrl: './manager.component.html',
  styleUrls: ['./manager.component.css']
})
export class ManagerComponent implements OnInit, OnDestroy {
  public viewName = ComponentViewEnm.MANAGER;
  public banners = [
    '业精于勤荒于嬉，行成于思毁于随。',
    '不取亦取，虽师勿师。',
    '单是说不行，要紧的是做。',
    '使人愉快的劳动，能医治心灵的创伤。'
  ];
  public articles: Array<ArticleInterface> = [];
  private subscribes: Array<Subscription> = [];
  constructor(
    private router: Router,
    private articlesManagerService: ArticlesManagerService,
    private modal: NzModalService,
    public CVMS: ComponetViewManagerService
  ) { }

  ngOnInit(): void {
    this.CVMS.setCurrentView(this.viewName);
    this.subscribes.push(this.articlesManagerService.articlesChange.subscribe({next: (res) => {
        this.articles = res;
    }}));
    this.articles = this.articlesManagerService.getArticles();
  }

  ngOnDestroy(): void {
    this.CVMS.destroyCurrentView(this.viewName);
    for (const vo of this.subscribes) {
      vo.unsubscribe();
    }
    this.articlesManagerService.destroy();
  }

  public delArticle(data): void {
    const id = data.id;
    this.modal.confirm({
      nzTitle: '您是否确认删除这篇文章?',
      nzContent: '',
      nzOkText: '是',
      nzOkType: 'danger',
      nzOnOk: () => {
        this.articlesManagerService.delArticle(id);
      },
      nzCancelText: '否',
      nzOnCancel: () => console.log('Cancel')
    });
  }


  public toCreateArticle(): void {
    this.router.navigateByUrl('/main/manager/create');
  }

  public editArticle(data): void {
    const id = data.id;
    this.router.navigateByUrl(`/main/manager/update/${id}`);
  }


  sliceTagName(tag: string): string {
    const isLongTag = tag.length > 20;
    return isLongTag ? `${tag.slice(0, 20)}...` : tag;
  }
}
